package com.fzq.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * redis对字符串数据的通用操作类
 */
@Component
public class RedisMapper {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 根据键保存字符串
     * @param key
     * @param val
     * @return
     */
    public boolean setKey(String key,String val){
        redisTemplate.opsForValue().set(key, val);
        if(redisTemplate.hasKey(key)){
           return true;
        }else{
           return false;
        }
    }

    /**
     * 根据键删除
     * @param key
     * @return
     */
    public boolean delKey(String key){
        if(redisTemplate.delete(key)){
          return true;
        }else{
          return false;
        }
    }

    /**
     * 添加并设置过期时间
     * @param key
     * @param val
     * @param timeout
     * @param unit
     * @return
     */
    public boolean setKey(String key,String val,long timeout, TimeUnit unit){
        redisTemplate.opsForValue().set(key, val,timeout,unit);
        if(redisTemplate.hasKey(key)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 根据键获得值
     * @param key
     * @return
     */
    public Object getKey(String key){
        if(redisTemplate.hasKey(key)){
            Object value=redisTemplate.opsForValue().get(key);
            return value;
        }else{
            return null;
        }
    }
}
